package com.bluegalaxy.nhb.snservice.core.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: nanhb
 * @Date: 2020/10/22 10:31
 * @Description:
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final Long default_expire_seconds = 86400L;  //24小时

    private static final Long default_expire_milliseconds = 86400000L; //24小时

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存
     */
    public boolean set(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存(设置过期时间 秒)
     */
    public boolean setExpire(final String key, String value,Long expire) {
        boolean result = false;
        try {
            if (expire == null){
                expire = default_expire_seconds;
            }
            redisTemplate.opsForValue().set(key,value,expire, TimeUnit.SECONDS );
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存(设置过期时间 毫秒)
     */
    public boolean setPexpire(final String key, String value,Long expire) {
        boolean result = false;
        try {
            if (expire == null){
                expire = default_expire_milliseconds;
            }
            redisTemplate.opsForValue().set(key,value,expire, TimeUnit.MILLISECONDS );
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public boolean getAndSet(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public boolean delete(final String key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
